﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;

namespace ViewMaker.Core.Wpf
{
    public static class TreeViewSelectedItemChangedBehavior
    {
        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(TreeViewSelectedItemChangedBehavior), new PropertyMetadata(CommandCallback));

        public static ICommand GetCommand(TreeView obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(TreeView obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        private static void CommandCallback(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var ele = obj as TreeView;
            if (ele != null)
            {
                ICommand cmd = (ICommand)args.NewValue;

                if (args.OldValue == null && args.NewValue != null)
                {
                    ele.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(SelectedItemChangedHandler);
                }
                else if (args.OldValue != null && args.NewValue == null)
                {
                    ele.SelectedItemChanged -= new RoutedPropertyChangedEventHandler<object>(SelectedItemChangedHandler);
                }
            }
        }

        static void SelectedItemChangedHandler(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var ele = e.OriginalSource as TreeView;
            ICommand cmd = (ICommand)ele.GetValue(CommandProperty);
            if (cmd != null) cmd.Execute(e.NewValue);
        }
    }

}
